#######################################################################
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# Openfuyao is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
#######################################################################

#!/bin/bash

# 脚本路径定义
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REDIS_DIR="${SCRIPT_DIR}/../redis"
CPU_TEST_BINARY="${SCRIPT_DIR}/../cputest.arm"

# 默认参数
TEST_TYPE="open"
TEST_RUN_TIMES=5  # 测试执行次数

# 帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -t <类型>      测试类型 (默认: open)"
    echo "  -h             显示此帮助信息"
    exit 0
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -t)
            TEST_TYPE="$2"
            shift 2
            ;;
        -h)
            show_help
            ;;
        *)
            echo "未知参数: $1" >&2
            show_help
            ;;
    esac
done

# 错误处理函数
handle_error() {
    echo "错误: $1 执行失败" >&2    
    exit 1
}

# 步骤1: 执行Redis自动化脚本
for ((i=1; i<=$TEST_RUN_TIMES; i++)); do
    echo "==== 执行redis自动化脚本 (第${i}次) ===="
    python3 "${REDIS_DIR}/auto_redis.py" -n 1 -r 50000000 -t ${TEST_TYPE} -sReq 1.9 -sLimit 2 -cReq 1.9 -cLimit 2 || handle_error "Redis自动化脚本"
    # 每轮测试间隔60s，减少因为清理资源造成的影响。
    sleep 60
done

# 步骤2: 给所有cpu加压（后台运行）
echo "==== 启动CPU加压 ===="
${CPU_TEST_BINARY} 0 0-127:50 &
STRESS_PID=$!
echo "CPU加压进程ID: ${STRESS_PID}"

# 等待加压生效
echo "等待240秒让加压生效..."
sleep 240

# 步骤3: 执行加压后Redis自动化脚本
for ((i=1; i<=$TEST_RUN_TIMES; i++)); do
    echo "==== 执行加压redis自动化脚本 (第${i}次) ===="
    python "${REDIS_DIR}/auto_redis.py" -n 1 -r 50000000 -t ${TEST_TYPE}-stress -sReq 1.9 -sLimit 2 -cReq 1.9 -cLimit 2 || handle_error "加压后Redis自动化脚本"
    sleep 60
done

# 停止CPU加压
echo "==== 停止CPU加压 ===="
kill -TERM ${STRESS_PID} 2>/dev/null
wait ${STRESS_PID} 2>/dev/null

echo "==== 所有步骤执行完成 ===="
exit 0